$(function () {
    BASE.USER_CENTER.getUserData();
});
var BASE = BASE||{};
BASE.USER_CENTER = (function () {
    var userInfo={};
    var cropper;
    var options={};
    /*根据来源显示页面*/
    function initShow() {
        var href = location.href;
        if(href.split('?flag=').pop() == 'fans'){
            $('#userContentNav .user-content-nav:eq(1)').trigger('click');
        }else {
            getNoticeList(1);
        }
    }
    /*用户导航点击切换下面的内容*/
    $('#userContentNav').on('click','a',function () {
        var id = $(this).data('id');
        $(this).addClass('checked').siblings().removeClass('checked');
        $('#'+id).show().siblings().hide();
    });
    /*钱包部分记录的切换*/
    $('.account-content').on('click','li.account-content-item',function () {
        var id = $(this).data('id');
        $(this).addClass('checked').siblings().removeClass('checked');
        $('#'+id).show().siblings().hide();
    });
    /*初始化用户页面*/
    function getUserData() {
        BASE.getHttp('/device/member/detail',function (res) {
            if(res.code!=200){
                location.href='/index.html';
                return;
            }
            var result = res.data.member;
            var link = location.origin+'/register.html';
            if(result.learnTypeIds){
                result.learnTypeNames = result.learnTypeNames.split(',');
                result.learnTypeIds = result.learnTypeIds.split(',');
            }else {
                result.learnTypeNames = [];
                result.learnTypeIds=[];
            }
            $('#box').show();
            userInfo = result;
            BASE.setStore('userInfo',userInfo);
            $('#userYcode').val('输入邀请码'+result.ycode+'注册编程达人，双方各获得20金币哦! '+link);
           /* $('#shareuserYcode').val('输入邀请码'+result.ycode+'注册编程达人，双方各获得20金币哦! '+link);*/
            $('#userData').html(template('userData_tpl',result));
            $('#userInfo').html(template('userInfo_tpl',result));
            $('#userWallet_balance').html(template('userWallet_balance_tpl',result));
            $('#bindMobile').html(template('bindMobile_tpl',result));
            if(!_canCheckIn()){
                $('#checkIn').html('已签到');
            }
            BASE.COMMON.userInfoFill();
            initShow();
        });
    }
    /*获取用户关注列表*/
    function getNoticeList(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
        };
        BASE.apiGet('/device/mfollow/listForMe',sendData,function (res) {
            $('#userNotice').html(template('userNotice_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getNoticeList,'userNotice');
        })
    }
    /*获取粉丝列表*/
    function getFans(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
        };
        BASE.apiGet('/device/mfollow/listFansForMe',sendData,function (res) {
            $('#userFans').html(template('userFans_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getFans,'userFans');
        })
    }
    /*获取项目列表*/
    function getMyProject(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
        };
        BASE.apiGet('/device/project/listForMe',sendData,function (res) {
            $('#userProject').html(template('userProject_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getMyProject,'userProject');
        })
    }
    /*我的源码*/
    function getMySource(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
            memberId:BASE.COMMON.getUserId(),
        };
        BASE.apiGet('/device/sourceCode/list',sendData,function (res) {
            $('#userSource').html(template('userSource_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getMySource,'userSource');
        })
    }
    /*删除源码*/
    function removeSource(id) {
        BASE.apiPost('/device/sourceCode/delete',{id:id},function (res) {
            BASE.clearpop('删除成功');
            getMySource(1);
        })
    }
    /*我的博客*/
    function getMyBlog(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
            memberId:BASE.COMMON.getUserId(),
        };
        BASE.apiGet('/device/blog/list',sendData,function (res) {
            $('#userBlog').html(template('userBlog_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getMyBlog,'userBlog');
        })
    }
    /*删除博客*/
    function removeBlog(id) {
        BASE.apiPost('/device/blog/delete',{id:id},function (res) {
            BASE.clearpop('删除成功');
            getMyBlog(1);
        })
    }
    /*获取收藏列表*/
    function getCollectList(page) {
        var $this = $(this);
        var type = $this.data('type');
        var flag = $this.data('flag');
        var sendData = {
            pageNum:page,
            pageSize:15,
            type:type || 1,
        };
        BASE.apiGet('/device/mcollect/list',sendData,function (res) {
            var tpl = template('userCollection_tpl'+type,{data:res.list});
            $('#userCollection .content').html(tpl);
            $('#userCollection .user-sub-nav-item').eq(type -1).addClass('checked').siblings('.user-sub-nav-item').removeClass('checked');
            $this.data('flag',true).addClass('checked').siblings('.user-sub-nav-item').removeClass('checked');
            paging(res.pageNum,res.pages,getNoticeList,'userCollection');
        })
    }
    /*获取我的提问*/
    function getMyQuestion(page) {
        var $this = $(this);
        var type = $this.data('type');
        var flag = $this.data('flag');
        var sendData = {
            pageNum:page,
            pageSize:15,
           /* title:type || true,*/
        };
        if(flag && $this[0].toString()!=='[object Window]'){
            return;
        }
        BASE.apiGet('/device/mutualQuestion/listForMe',sendData,function (res) {
            var tpl = template('userQuestion_tpl',{data:res.list});
            $('#userQuestion .content').html(tpl);
            $this.data('flag',true).addClass('checked').siblings('.user-sub-nav-item').removeClass('checked');
            paging(res.pageNum, res.pages, getMyQuestion, 'userQuestion');
        })
    }
    /*获取我的回答*/
    function getMyAnswer(page) {
        var $this = $(this);
        var type = $this.data('type');
        var flag = $this.data('flag');
        var sendData = {
            pageNum:page,
            pageSize:15,
            /* title:type || true,*/
        };
        if(flag && $this[0].toString()!=='[object Window]'){
            return;
        }
        BASE.apiGet('/device/mutualAnswer/listByMemberId',sendData,function (res) {
            var tpl = template('userAnswer_tpl',{data:res.list});
            $('#userAnswer .content').html(tpl);
          /*  $this.data('flag',true).addClass('checked').siblings('.user-sub-nav-item').removeClass('checked');*/
            paging(res.pageNum, res.pages, getMyAnswer, 'userAnswer');
        })
    }
    /*删除回答*/
    function removeAnswer(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/mutualAnswer/delete',{id:id},function (res) {
            BASE.clearpop('删除成功');
            getMyAnswer(1);
        })
    }
    /*删除提问*/
    function removeQues(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/mutualQuestion/delete',{id:id},function (res) {
            BASE.clearpop('删除成功');
            getMyQuestion(1);
        })
    }
    /*获取订单列表*/
    function getOrderList(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        if(flag && $this[0].toString()!=='[object Window]'){
            return;
        }
        var sendData = {
            pageNum:page,
            pageSize:15,
            type:1,
        };
        BASE.apiGet('/device/morder/list',sendData,function (res) {
            $('#userOrder').html(template('userOrder_tpl',{data:res.list}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getOrderList,'userOrder');
        })
    }
    /*修改用户资料前的数据展示*/
    function modifyUserDataPrev() {
        BASE.COMMON.getArea(2,'provinceId','',function () {
            if(userInfo.provinceId){
                $('#provinceId').val(userInfo.provinceId);
                BASE.COMMON.getArea(3,'cityId',userInfo.provinceId,function () {
                    $('#cityId').val(userInfo.cityId);
                    if(userInfo.cityId){
                        BASE.COMMON.getArea(4,'areaId',userInfo.cityId,function () {
                            $('#areaId').val(userInfo.areaId);
                        })
                    }
                });
            }
        });

        _getInterest();
        $('#userInfo').show()
    }
    /*修改用户资料*/
    function modifyUserData(sendData) {
        if(!sendData){
            sendData = _getModifyData();
        }
         BASE.apiPost('/device/member/update',sendData,(function () {
            $('#userInfo').hide();
             getUserData();
        }))
    }

    /*获取兴趣方向*/
    function _getInterest(parentId,callback) {
        var sendData = {
            parentId:parentId,
        };
        BASE.apiGet('/device/mainCategory/list', sendData,function (data) {
            if(callback &&typeof callback=='function'){
                callback(data);
                return;
            }
            var result = _initInterestData(data);
            $('#interestData').html(template('interestData_tpl',{data:result}));
        });
    }
    /*根据兴趣方向主分类获取下级*/
    function selectInterestPrarent(id) {
        _getInterest(id,function (data) {
            $('#interestChildData').html(template('interestChildData_tpl',{data:data}));
        })
    }
    /*选择兴趣方向*/
    function selectInterest() {
        var length =$('#userInterest .selected-interest-item').length;
        if( length>=5 ){
            BASE.clearpop('最多选择5个方向');
            return;
        }
        var $this = $('#interestChildData option:selected');
        var id = $this.val();
        var name = $this.text().trim();
        var learnTypeNames = _getInterestres().names;
        var learnTypeIds = _getInterestres().ids;
        learnTypeNames.push(name);
        learnTypeIds.push(id);
        var result = {
            learnTypeNames:learnTypeNames,
            learnTypeIds:learnTypeIds,
        };
        $('#userInterest').html(template('userInterest_tpl',{data:result}));
    }
    /*获取的兴趣方向的数据处理*/
    function _initInterestData(arr) {
        var result = [];
        arr.forEach(function (item) {
            if (item.parentId === '0') {
                result.push(item);
            }
        });
        return result;
    }
    /*获取用户修改的数据*/
    function _getModifyData() {
        var $input = $('#userInfo input[data-id]');
        var $select = $('#userInfo select[data-id]');
        var result = {};
        result = _getKindData(result,$input);
        result = _getKindData(result,$select);
        result.learnTypeIds = _getInterestres().ids.join(',');
        return result;
    }
    /*获取选择的兴趣爱好的数据*/
    function _getInterestres() {
        var  $interest = $('#userInterest button');
        var ids = [];
        var names = [];
        $interest.each(function () {
            ids.push($(this).data('id'));
            names.push(($(this).text().trim()));
        });
        return {
            ids:ids,
            names:names,
        }
    }
    /*获取用户某种选项数据*/
    function _getKindData(result,obj) {
        obj.each(function () {
            var $this = $(this);
            var keys = $this.data('id');
            var values = $this.val();
            keys = _initDataKeys(keys);
            result[keys] = values;
        });
        return result;
    }
    /*修改数据的键值处理*/
    function _initDataKeys(keys) {
        if(!keys){
            return;
        }
        var keys0 = keys.split('_')[0];
        var keys1 = keys.split('_')[1] || '';
        if(keys1){
            keys1 = keys1.substring(0,1).toUpperCase()+keys1.substring(1);
        }
        return keys0 + keys1;
    }

    /*头像上传前的预览*/
    function previewImg(obj) {
        var file=obj.files[0],
            reader=new FileReader();
        reader.onload=function (e) {
            var img=document.getElementById('img');
            img.setAttribute('src',e.target.result);
            img.onload=function () {
                var $image = $(img);
                $('#modifyHeader').show();
                $image.cropper({
                    aspectRatio: 5 / 4,
                    crop: function(event){
                        options={
                            aspectRatio:5 / 5,
                            originalHeight:$image.height(),
                            canvasWidth:event.width,
                            canvasHeight:event.height,
                            scaledWidth:event.width*event.scale,
                            scaledHeight:event.height*event.scale,
                            scaledRatio:event.scale
                        }
                    }
                });
                cropper = $image.data('cropper');
            }
        };
        reader.readAsDataURL(file);
    }

    /*确认修改头像   */
    function sureUpHeader() {
        var c=cropper.getCroppedCanvas(options);
        var imgData=c.toDataURL('image/jpeg');
        var formData = new FormData();
        var bob = BASE.UPLOAD.getBob(imgData);
        var imageFile = new File([bob],'1.png',{type:"image/jpeg"});
        formData.append("imageFile",imageFile);
        //头像header,身份证idcard,video视频相关,course课程相关,question问题相关,training作业,bbs相关)
        formData.append('code','header');
        BASE.UPLOAD.upLoadImg(formData,function (res) {
            closeHeader();
            modifyUserData({header:res});
            getUserData();
        })
    }
    /*取消头像上传*/
    function closeHeader() {
        cropper.destroy();
        $('#modifyHeader').hide();
    }
    /*签到*/
    function checkIn(obj) {
        if(!_canCheckIn()){
            return;
        }
        BASE.setStore('chekInDate',Date.now());
        BASE.apiPost('/device/member/checkIn',function () {
            BASE.setStore('chekInDate',Date.now());
            $(obj).text('签到成功');
        })
    }
    /*是否可以签到*/
    function _canCheckIn() {
        var cachechekInDate = BASE.getStore('chekInDate');
        if(!cachechekInDate) {
            return true;
        }
        cachechekInDate = JSON.parse(cachechekInDate);
        return Date.now() - _getYMDtimes(cachechekInDate) >0
    }
    /*获取年月日的时间戳*/
    function _getYMDtimes(times) {
        var date = new Date(times);
        var y = date.getFullYear();
        var M =  date.getMonth() + 1;
        var d =  date.getDate();
        return new Date(y+'-'+M+'-'+d+' 24:00:00').getTime();
    }
    /*复制邀请码*/
    function copyYcode() {
        var url = document.getElementById("userYcode");
        url.select(); // 选择对象v
     /*   var data = document.getElementById("shareuserYcode");
        data.select(); // 选择对象v*/
        document.execCommand("Copy"); // 执行浏览器复制命令
       /* */
        BASE.clearpop('复制成功');
      
    }
    /*获取我的交易记录*/
    function getDealList(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        var sendData = {
                pageNum:page,
                pageSize:15,
               /* beginDateTime
                endDateTime*/
                specDateMonth:$('#dealList').data('spec_date_month'),
            };
        if(flag && $this[0].toString()!=='[object Window]'){
            return;
        }
        BASE.apiGet('/device/mmoneyRecords/list',sendData,function (res) {
            var data = {
                list:res.pageInfo.list,
                sumMap:res.sumMap||{},
            };
            if(sendData.specDateMonth){
                data.sumMap.month =  $('#dealList').data('date');
            }
            $('#dealList').html(template('dealList_tpl',{data:data}));
            $('#txt_calendar').attr('data-max-year',new Date().getFullYear());
            $('#txt_calendar').attr('data-min-year',new Date().getFullYear() - 3);
            var myDate1 = new dateyearmonth({
                id:'txt_calendar',
                callback:function (val) {
                    var time = new Date(val+'-01').getTime();
                    $('#dealList').data('spec_date_month',time);
                    $('#dealList').data('date',val);
                    getDealList(1);
                }
            });
            paging(res.pageInfo.pageNum,res.pageInfo.pages,getDealList,'dealList');
            $this.data('flag',true);
        })
    }
    /*获取提现记录*/
    function getWithdrawList(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        var sendData = {
            pageNum:page,
            pageSize:15,
            /* beginDateTime
             endDateTime*/
            specDateMonth:$('#withdraw').data('spec_date_month'),
        };
        if(flag && $this[0].toString()!=='[object Window]'){
            return;
        }
        BASE.apiGet('/device/withdraw/list',sendData,function (res) {
            $('#withdraw').html(template('withdraw_tpl',{data:res.pageInfo}));
            paging(res.pageInfo.pageNum,res.pageInfo.pages,getWithdrawList,'withdraw');
            $this.data('flag',true);
        })
    }
    /*获取送心意记录*/
    function getGiftList(page) {
        var $this = $(this);
        var flag = $this.data('flag');
        var sendData = {
            pageNum:page,
            pageSize:15,
        };
        if(flag&& $this[0].toString()!=='[object Window]'){
            return;
        }
        BASE.apiGet('/device/heart/listGiveMe',sendData,function (res) {
            var data = {
                list:res.list,
            };
            $('#giftList').html(template('giftList_tpl',{data:data}));
            paging(res.pageNum,res.pages,getGiftList,'giftList');
            $this.data('flag',true);
        })
    }
    /*日历时间选择后*/
    function selectMonth(obj) {
        var val = $(obj).val();
        var time = new Date(val+'-01').getMilliseconds();
        $('#dealList').data('spec_date_month',time);
        getDealList(1);
    }
    /*准备去提现前*/
    function toWithdrawPrev(obj) {
        var userInfo = BASE.getStore('userInfo');
        if(!userInfo){
            BASE.clearpop('登录异常请重新登录');
            return;
        }
        var money =  $(obj).data('money');
        var tel = userInfo.mobile;
        if(!userInfo.realName){
            BASE.clearpop('请先完善资料');
            $('#userInfo').show();
            return;
        }
        if(!tel){
            BASE.clearpop('请先绑定手机');
            $('#bindMobile').show();
            return;
        }
        location.href = '/userWithdraw.html?money='+money;
    }
    /*手机号绑定*/
    function bindTel() {
        var sendData = {
            vcode:$('#vcode').val(),
            mobile:$('#tel').val()
        };
        if(!sendData.vcode){
            BASE.clearpop('请填写验证码');
            return;
        }
        BASE.apiPost('/device/member/bindMobile',sendData,function (res) {
            BASE.clearpop('绑定成功');
            $('#vcode').val('');
            $('#tel').val('');
            $('#bindMobile').hide();
            getUserData();
        })
    }
    return {
        initShow:initShow,
        getUserData:getUserData,
        getNoticeList:getNoticeList,
        getFans:getFans,
        getMyProject:getMyProject,
        getCollectList:getCollectList,
        getMyQuestion:getMyQuestion,
        removeAnswer:removeAnswer,
        removeQues:removeQues,
        getMyAnswer:getMyAnswer,
        getOrderList:getOrderList,
        getMySource:getMySource,
        removeSource:removeSource,
        getMyBlog:getMyBlog,
        removeBlog:removeBlog,
        modifyUserDataPrev:modifyUserDataPrev,
        modifyUserData:modifyUserData,
        selectInterestPrarent:selectInterestPrarent,
        selectInterest:selectInterest,
        previewImg:previewImg,
        sureUpHeader:sureUpHeader,
        checkIn:checkIn,
        copyYcode:copyYcode,
        getDealList:getDealList,
        getWithdrawList:getWithdrawList,
        getGiftList:getGiftList,
        selectMonth:selectMonth,
        closeHeader:closeHeader,
        toWithdrawPrev:toWithdrawPrev,
        bindTel:bindTel,
    }
})();


